﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Speech.Recognition;

namespace einuorg_console
{
    class UDPserver
    {
        private static string DatePattern = "HH:mm:ss";
        public static void Initialize(string IPaddress, int port)
        {
            Boolean done = false;
            Boolean exception_thrown = false;
            Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPAddress sendto_address = IPAddress.Parse(IPaddress);
            IPEndPoint sending_endpoint = new IPEndPoint(sendto_address, port);

            Terminal.Brackets(DateTime.Now.ToString(DatePattern), Terminal.BracketState.Success);
            Terminal.WriteLine("einuorg.UDPserver Initialized on address " + IPaddress + ":" + port.ToString());
            while (!done)
            {
                Terminal.Brackets("--:--:--", Terminal.BracketState.Default);

                string text_to_send = Terminal.ReadLine();

                if (text_to_send.Length == 0)
                {
                    done = true;
                }
                else
                {
                    byte[] sendbuffer = Encoding.ASCII.GetBytes(text_to_send);
                    try
                    {
                        sending_socket.SendTo(sendbuffer, sending_endpoint);
                    }

                    catch (Exception send_exception)
                    {
                        exception_thrown = true;
                        Terminal.Write("\r");
                        Terminal.Brackets(DateTime.Now.ToString(DatePattern), Terminal.BracketState.Error);
                        Terminal.WriteLine(send_exception.Message);
                    }

                    if (exception_thrown == false)
                    {
                        Terminal.Write("\r");
                        Terminal.Brackets(DateTime.Now.ToString(DatePattern), Terminal.BracketState.Warning);
                        Terminal.WriteLine(text_to_send);
                    }
                    else
                    {
                        exception_thrown = false;
                        Terminal.Write("\r");
                        Terminal.Brackets(DateTime.Now.ToString(DatePattern), Terminal.BracketState.Error);
                        Terminal.WriteLine("Sending failed.");
                    }
                }
            }
        }
    }
}
